
package gui;

import java.awt.FlowLayout;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

import server.Protocol;

public class MyFrame extends JFrame implements ActionListener {
	private JTextField actionTf;
	private JTextField fromTf;
	private JTextField toTf;
	private JTextField contentTf;
	private JButton sendBtn;
	private JTextArea infTa;
	
	private Socket socket;
	private ObjectOutputStream out;
	private ObjectInputStream in;
	
	public MyFrame() {
		this.setSize(320, 400);
		this.setResizable(false);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		init();
		addEvent();
		
		new Thread(){
			public void run() {
				while(true){
					connect();
					try {
						Object o=in.readObject();
						infTa.append(o.toString()+"\n");
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			};
		}.start();
		this.setVisible(true);
	}
	private void init(){
		this.setLayout(new FlowLayout());
		actionTf=new JTextField("1",20);
		fromTf=new JTextField("john",20);
		toTf=new JTextField("tom",20);
		contentTf=new JTextField("content",20);
		sendBtn=new JButton("send");
		infTa=new JTextArea(10,20);
		JLabel lab1=new JLabel("动作:");
		this.add(lab1);
		this.add(actionTf);
		JLabel lab2=new JLabel("从哪:");
		this.add(lab2);
		this.add(fromTf);
		JLabel lab3=new JLabel("到哪:");
		this.add(lab3);
		this.add(toTf);
		JLabel lab4=new JLabel("内容:");
		this.add(lab4);
		this.add(contentTf);
		this.add(sendBtn);
		this.add(infTa);
	}
	public void connect(){
		try {
			socket=new Socket("127.0.0.1",8000);
			out=new ObjectOutputStream(socket.getOutputStream());
			in=new ObjectInputStream(socket.getInputStream());
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private void addEvent(){
		sendBtn.addActionListener(this);
	}
	
	public static void main(String[] args) {
		new MyFrame();
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		Protocol p=new Protocol();
		p.setAction(Integer.parseInt(actionTf.getText()));
		p.setFrom(fromTf.getText());
		p.setTo(toTf.getText());
		p.setContent(contentTf.getText());
		try {
			out.writeObject(p);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}
}





